import {Http} from "./http";

class Paging {

    start
    count
    req
    url
    locker = false // 没锁住：能进行请求    true代表锁住：不能进行请求
    moreData = true
    accumulator = []

    constructor(req, start = 0, count = 5) {
        this.req = req
        this.start = start
        this.count = count
        this.url = req.url
    }

    async getMoreData() {
        //getLocker request releaseLocker
        // if (this._getLocker()) {
        //     //该请求是一定成功的，要么取得数据data，要么data={}并且服务器修改header响应状态404，该异常捕获不了
        //     const result = await Http.request({
        //         url: this.url + this.count
        //     })
        //     this._releaseLocker()
        //     return result.data
        // }
        // return {}
        if (!this.moreData) {
            return
        }
        if (!this._getLocker()) {
            return;
        }
        const data = await this._actualGetData()
        this._releaseLocker()
        return data
    }

    async _actualGetData() {
        const req = this._getCurrentReq()
        let paging = await Http.request(req)
        paging = paging.data
        if (!paging) {
            return null
        }
        if (paging.total === 0) {
            return {
                empty: true,
                items: [],
                moreData: false,
                accumulator: []
            }
        }
        this.moreData = Paging._moreData(paging.total_page, paging.page)
        if (this.moreData) {
            // this.start += this.count
            this.count += 5
        }
        this._accumulate(paging.items)
        return {
            empty: false,
            items: paging.items,
            moreData: this.moreData,
            accumulator: this.accumulator
        }
    }

    _accumulate(items) {
        this.accumulator = this.accumulator.concat(items)
    }

    static _moreData(totalPage, pageNum) {
        return pageNum < totalPage - 1
    }

    _getCurrentReq() {
        let url = this.url + this.count
        // const params = `start=${this.start}&count=${this.count}`
        // url = v1/spu/latest + '?' + params
        // url = v1/spu/latest?other=abc + '&' +params
        // if (url.indexOf('?') !== -1) {
        //     url += '&' + params
        // }
        // else {
        //     url += '?' + params
        // }
        this.req.url = url
        return this.req
    }

    _getLocker() { // 表示能否进行请求
        if (this.locker) {
            return false
        }
        this.locker = true
        return true
    }

    _releaseLocker() {
        this.locker = false
    }

}

export {
    Paging
}